package com.simple.utils;

import java.io.BufferedWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.simple.entity.SysTable;
/**
 * 代码生成工具类
 * 
 * **/
@Component
public class GenerateUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(GenerateUtils.class);

	//传输的内容：存放表信息的list,和表名称
	public static String projectPath=System.getProperty("user.dir")+"/src/main/java/com/blog";
//	public static String projectPath="E:/note"; //测试环境
	
	public static String projectHtmlPath=System.getProperty("user.dir")+"/src/main/resources/templates";
	
	public static String packageName="com.simple";
	
	public static void generateFile(List<SysTable> list,String tableName,String databaseName,String title,String isHtml) {
		
		String entityName=MyStringUtils.lowerNameToEntity(tableName,true);
		String objectName=MyStringUtils.lowerNameToEntity(tableName,false);
		//模板文件和生成的文件
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("Entity.vm", projectPath+"/entity/"+entityName+".java");
		map.put("Repository.vm", projectPath+"/repository/"+entityName+"Repository.java");
		map.put("Service.vm", projectPath+"/service/"+entityName+"Service.java");
		map.put("ServiceImpl.vm", projectPath+"/service/impl/"+entityName+"ServiceImpl.java");
		map.put("Controller.vm", projectPath+"/controller/"+entityName+"Controller.java");
		map.put("TableHtml.vm", System.getProperty("user.dir")+"/src/main/resources/templates/"+entityName+".html");
		map.put("EditHtml.vm",System.getProperty("user.dir")+"/src/main/resources/templates/"+entityName+"Edit.html");
		//关键字搜索
		List<String> searchWordList=new LinkedList<String>();
		StringBuffer searchWordString=new StringBuffer();
		StringBuffer searchWordNoType=new StringBuffer();
		StringBuffer searchWordHtml=new StringBuffer();
		StringBuffer formDataHtml=new StringBuffer();
		for (SysTable sysTable : list) {
			//搜索属性
			if(sysTable.getColumnSearch()==1) {
				searchWordList.add(sysTable.getColumnEntityName());
				searchWordString.append("String "+sysTable.getColumnEntityName()+",");
				searchWordNoType.append(sysTable.getColumnEntityName()+",");
				searchWordHtml.append(sysTable.getColumnEntityName()+":"+sysTable.getColumnEntityName()+",");
			}
			//表单属性
			if(sysTable.getColumnEdit()==1) {
				formDataHtml.append("'"+sysTable.getColumnEntityName()+"':"+objectName+"."+sysTable.getColumnEntityName()+",");
			}
		}
		logger.info("searchWordList:"+searchWordList);
		logger.info("searchWordString:"+searchWordString);
		for (String key : map.keySet()) {
			String targetFile=(String) map.get(key);//文件输出
			VelocityEngine velocityEngine = new VelocityEngine();
			velocityEngine.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, System.getProperty("user.dir")+"/src/main/resources/velocity");
			velocityEngine.setProperty("input.encoding", "utf-8");
			velocityEngine.setProperty("output.encoding", "utf-8");
			velocityEngine.init();
			
			Template template = velocityEngine.getTemplate(key);
			VelocityContext vc = new VelocityContext();
			vc.put("propertyList", list);
			vc.put("packageName", packageName);
			//实体名称 例：SysUser
			vc.put("entityName", entityName);
			//对象名称 例：sysUser
			vc.put("objectName",objectName );
			vc.put("tableName", tableName);
			vc.put("databaseName", databaseName);
			vc.put("searchWordList", searchWordList);
			vc.put("searchWordString", MyStringUtils.commaString(searchWordString));
			vc.put("searchWordNoType", MyStringUtils.commaString(searchWordNoType));
			vc.put("searchWordHtml", MyStringUtils.commaString(searchWordHtml));
			vc.put("formDataHtml", MyStringUtils.commaString(formDataHtml));
			//选择生成页面
			if(isHtml.contains("1")) {
				vc.put("title", title);
			}else {
				continue;
			}
			File file = new File(targetFile);
			if (!file.getParentFile().exists())
                file.getParentFile().mkdirs();
	        FileOutputStream outStream;
			try {
				outStream = new FileOutputStream(file);
				OutputStreamWriter writer = new OutputStreamWriter(outStream, "UTF-8");
		        BufferedWriter bufferedWriter = new BufferedWriter(writer);
		        template.merge(vc, bufferedWriter);
		        bufferedWriter.flush();
		        bufferedWriter.close();
		        outStream.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
